from contextlib import contextmanager

#contextmanager实现上下文
class Test:
    def qu(self):
        print('data')
@contextmanager
def auto_test():
    print('前置操作')
    yield Test()
    print('后置操作')

with auto_test() as r:
    r.qu()

#上下文使用
class MyResource:
    def __enter__(self):
        print('前置操作')
        return self

    def __exit__(self, exc_type, exc_value, tb):
        print('前置操作')

    def quert(self):
        print('data')

with MyResource() as r:
    r.quert()


#contextmanager 灵活使用



@contextmanager
def book_mark():
    print('《',end='') #先执行这个
    yield #到这里函数暂时中止，运行with里面的代码
    print('》',end='') #最后执行这个

with book_mark() :
    print('三体',end='')


